import { defineStore } from "pinia";
import { RouteLocationNormalized } from "vue-router";
import { TABS_ROUTES } from "../mutation-types";
import { storage } from "@/utils/Storage";

// 不需要出现在标签页中的路由
const whiteList = ["Redirect", "Login"];

// Partial<T> 可以快速把某个接口类型中定义的属性变成可选的(Optional)：
export type RouteItem = Partial<RouteLocationNormalized> & {
  fullPath: string;
  name: string;
};

export type ITabsViewState = {
  tabsList: RouteItem[]; // 标签页
};

export const useTabsViewStore = defineStore({
  id: "app-tabs-view",
  state: (): ITabsViewState => ({
    tabsList: [],
  }),
  getters: {},
  actions: {
    // 初始化标签页
    initTabs(routes) {
      this.tabsList = routes;
    },
    // 添加标签页
    addTabs(route): boolean {
      if (whiteList.includes(route.name)) return false;
      //some()是对数组中每一项运行给定函数，如果该函数对任一项返回true，则返回true。
      const isExists = this.tabsList.some(
        (item) => item.fullPath == route.fullPath
      );
      if (!isExists) {
        this.tabsList.push(route);
      }
      return true;
    },
    // 关闭左侧
    closeLeftTabs(route) {
      // findIndex()方法用于找到数组中第一个符合条件的元素的下标，如果所有成员都不符合条件，则返回-1
      const index = this.tabsList.findIndex(
        (item) => item.fullPath == route.fullPath
      );
      this.tabsList.splice(0, index);
    },
    // 关闭右侧
    closeRightTabs(route) {
      const index = this.tabsList.findIndex(
        (item) => item.fullPath == route.fullPath
      );
      this.tabsList.splice(index + 1);
    },
    // 关闭其他
    clostOtherTabs(route) {
      this.tabsList = this.tabsList.filter(
        (item) => item.fullPath == route.fullPath
      );
    },
    // 关闭当前页
    closeCurrentTab(route) {
      const index = this.tabsList.findIndex(
        (item) => item.fullPath == route.fullPath
      );
      this.tabsList.splice(index, 1);
    },
    // 关闭全部
    closeAllTabs() {
      this.tabsList = [];
      storage.remove(TABS_ROUTES);
    },
  },
});
